<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------

namespace api\toilet\logic;

use api\admin\model\BandToiletModel;
use api\admin\model\ToiletModel;
use think\cache\driver\Redis;

class PushModel extends ToiletModel
{

    public $token = "49BB441C81E44AD5AF5372D02AC06E0B";

    /**
     * [filterData 筛选数据]
     * @param  [type] $config [配置的推送]
     * @param  [type] $data   [推送的数据mac]
     * @return [type]         [description]
     */
    public function getFilterData($config, $data)
    {

        $result = [];
        foreach ($data as $key => $value)
        {

            $mac = trim(strtoupper(str_replace(":", "", $value['mac'])));

            if (isset($config[$mac]) && $config[$mac])
            {

                $result[trim($value['mac'])] = $config[$mac];

            }
            else
            {
                unset($data[$key]);
                //记录异常mac
                cmf_log("[" . date('Y-m-d H:i:s', time()) . "]" . "不存在/未配置---" . $mac . PHP_EOL, RUNTIME_PATH . 'push/noMac.log');
            }

        }

        return $result;
    }

    /**
     * [getPushData 辨识推送数据]
     * @param  [type] $filterData [description]
     * @return [type]             [description]
     */
    public function getPushData($filterData)
    {

        $band = new BandToiletModel();

        //
        foreach ($filterData as $key => $value)
        {

            $flow   = $band->where(['master_mac' => $key, 'mac_device_type' => '1'])->count();
            $device = $band->where(['master_mac' => $key, 'mac_device_type' => '2'])->count();
            $sensor = $band->where(['master_mac' => $key, 'mac_device_type' => '3'])->count();

            // //流量设备推送
            if ($flow)
            {
                $this->pushFlowData($key, $value);
            }

            //坑位设备推送
            if ($device)
            {
                $this->pushDeviceData($key, $value);
            }

            // 环境数据推送
            if ($sensor)
            {
                $this->pushSensorData($key, $value);
            }

            //记录推送设备
            $log = "【" . $key . "】:执行推送:包含流量设备--$flow,包含坑位设备--$device,包含环境设备--$sensor";
            cmf_log("[" . date('Y-m-d H:i:s', time()) . "]" . $log . PHP_EOL, RUNTIME_PATH . 'push/pushMac.log');

        }

    }

    /**
     * [pushDeviceData 设备坑位推送]
     * @param  [type] $mac       [description]
     * @param  [type] $stationId [description]
     * @return [type]            [description]
     */
    public function pushDeviceData($mac, $stationId)
    {

        $baseUrl = "http://58.49.165.13:86/api/ToiletRemain/UploadRemainData?";
        $baseUrl .= "token=" . $this->token . "&no=" . mt_rand(10000000, 99999999);

        $deviceMan = $this->deviceToEasy($this->getCloudMacData($mac."_device_man"));
        $deviceWoman = $this->deviceToEasy($this->getCloudMacData($mac."_device_woman"));


         //组装数据
        $param = json_encode(

            [
                'stationId' => $stationId,
                'dataTime' => date('Y-m-d H:i:s', time()),
                'data' => [
                    [
                        'manLeft'=>$this->toiletSurplus($deviceMan),
                        'woManLeft'=>$this->toiletSurplus($deviceWoman),
                        'wManStatus'=>array_values($this->getToiletPushData($deviceMan)),
                        'wWomanStatus'=>array_values($this->getToiletPushData($deviceWoman,'woman')),
                    ],
                ],
            ]

        );

        // print_r($param);exit;
        $headers = [
            'Content-Type: application/json',
            'Content-Length: ' . strlen($param),
        ];

        $result = $this->myCurl($baseUrl, $param, $headers);
        $log = "[--".$mac."--]"."【----{json_encode($param)}-----】";
        cmf_log("[" . date('Y-m-d H:i:s', time()) . "]" .$log. $result . PHP_EOL, RUNTIME_PATH . 'push/pushDeviceData.log');
        return $result;


    }

    /**
     * 组装数据集
     */
    public function getToiletPushData($data,$type = 'man')
    {

        @array_multisort(array_column($data, 'order'), SORT_ASC, $data);

        $result = [];
        if (!empty($data)) {

            $str = $type == 'man' ? 0:1;
            $result = [];
            foreach ($data as $key => $value) {

                $result[$key] = ['wCsnName'=>$str.$value['order'],'status'=>$value['zsta']];

            }

        }

        return $result;
    }

    /**
     * [manLeft 计算余量]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function toiletSurplus($data)
    {   
        
        $count = 0;
        if (!empty($data)) {

            $other = [];
            foreach ($data as $key => $value) {
                
                if ($value['zsta']) {
                    $other[$key] = $value['zsta'];
                }
            }
            $count = count($data)-count($other);
        }
        return $count;
    }


    /**
     * [pushFlowData 推送流量数据]
     * @param  [type] $mac       [description]
     * @param  [type] $stationId [description]
     * @return [type]            [description]
     */
    public function pushFlowData($mac, $stationId)
    {

        $baseUrl = "http://58.49.165.13:86/api/Traffic/UploadTrafficData?";
        $baseUrl .= "token=" . $this->token . "&no=" . mt_rand(10000000, 99999999);

        $redisResult = $this->getCloudMacData($mac);

        //获取传感器数据
        $flow      = $this->getCloudDeviceData($redisResult, $mac, 'flow');
        $flowMan   = $flow['man'];
        $flowWoman = $flow['woman'];
        if (!empty($flowMan) && !empty($flowWoman))
        {
            $manCount   = isset($flowMan['today']) ? $flowMan['today'] : 0;
            $womanCount = isset($flowWoman['today']) ? $flowWoman['today'] : 0;
            $count      = $manCount + $womanCount;
        }
        else
        {

            $redis = new \Redis();
            $redis->connect('127.0.0.1', 6379);
            $count = $redis->get('cloud_' . $mac."_flow_other_today_flow");
        }



         //组装数据
        $param = json_encode(

            [
                'stationId' => $stationId,
                'dataTime' => date('Y-m-d H:i:s', time()),
                'data' => [
                    [
                        'pFlowCount'=>$count
                    ],
                ],
            ]

        );

        $headers = [
            'Content-Type: application/json',
            'Content-Length: ' . strlen($param),
        ];

        $result = $this->myCurl($baseUrl, $param, $headers);


        $log = "[--".$mac."--]";
        cmf_log("[" . date('Y-m-d H:i:s', time()) . "]" .$log. $result . PHP_EOL, RUNTIME_PATH . 'push/pushFlowData.log');
        return $result;
    }

    /**
     * [pushData 推送信息到武汉平台]
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public function pushSensorData($mac, $stationId)
    {
        $baseUrl = "http://58.49.165.13:86/api/Collect/UploadSensorData?";
        $baseUrl .= "token=" . $this->token . "&no=" . mt_rand(10000000, 99999999);

        $redisResult = $this->getCloudMacData($mac);
        //获取传感器数据
        $sensor = $this->getCloudDeviceData($redisResult, $mac, 'sensor');

        $sensorMan   = $sensor['man'];
        $sensorWoman = $sensor['woman'];

        //组装数据
        $param = json_encode(

            [
                'stationId' => $stationId,
                'dataTime' => date('Y-m-d H:i:s', time()),
                'data' => [
                    [
                        'mTemperature' => !empty($sensorMan['temperature']) ? $sensorMan['temperature'] : 0, //温度
                        'mHumidity' => !empty($sensorMan['humidity']) ? $sensorMan['humidity'] : 0, //湿度
                        'mAmmonia' => !empty($sensorMan['NH3']) ? $sensorMan['NH3'] : 0, //氨气
                        'mHydrogenSulfide' => !empty($sensorMan['H2S']) ? $sensorMan['H2S'] : 0, //硫化氢
                        'wTemperature' => !empty($sensorWoman['temperature']) ? $sensorWoman['temperature'] : 0,
                        'wHumidity' => !empty($sensorWoman['humidity']) ? $sensorWoman['humidity'] : 0, //湿度
                        'wAmmonia' => !empty($sensorWoman['NH3']) ? $sensorWoman['NH3'] : 0, //氨气
                        'wHydrogenSulfide' => !empty($sensorWoman['H2S']) ? $sensorWoman['H2S'] : 0, //硫化氢
                    ],
                ],
            ]

        );

        $headers = [
            'Content-Type: application/json',
            'Content-Length: ' . strlen($param),
        ];

        $result = $this->myCurl($baseUrl, $param, $headers);
        cmf_log("[" . date('Y-m-d H:i:s', time()) . "]" . $result . PHP_EOL, RUNTIME_PATH . 'push/pushSensorData.log');
        return $result;
    }
    /**
     * [getAuthToken curl 通用函数]
     * @Author   HUI
     * @DateTime 2019-01-22
     * @version  [version]
     * @param    [type]     $uri    [description]
     * @param    [type]     $post   [description]
     * @param    [type]     $header [description]
     * @return   [type]             [description]
     */
    public function myCurl($uri, $param, $headers)
    {
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $uri);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 1);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, 1);
        //设置post数据
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $param);
        //执行命令
        $data = curl_exec($curl);
        //显示获得的数据
        if (curl_getinfo($curl, CURLINFO_HTTP_CODE) == '200')
        {
            $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
            $header     = substr($data, 0, $headerSize);
            $body       = substr($data, $headerSize);
        }
        //关闭URL请求
        curl_close($curl);
        // print_r($data);exit();
        if (isset($body) && !empty($body))
        {
            return $body;
        }
        else
        {
            return false;
        }

    }
    
    /**
     * [getCloudDeviceData 获取redis对应数据]
     * @param  [type] $redisResult [description]
     * @param  [type] $mac         [description]
     * @param  [type] $deviceType  [description]
     * @return [type]              [description]
     */
    public function getCloudDeviceData($redisResult, $mac, $deviceType)
    {

        $man   = [];
        $woman = [];

        if (!empty($redisResult))
        {

            //获取男厕传感器数值
            if (!empty($redisResult['cloud_' . $mac . "_" . $deviceType . "_man"]))
            {

                $sensorManRes = @unserialize($redisResult['cloud_' . $mac . "_" . $deviceType . "_man"]);
                if (!empty($sensorManRes))
                {

                    foreach ($sensorManRes as $key => $value)
                    {

                        $man = @unserialize($value);

                    }
                }

            }

            //获取女厕传感器数值
            if (!empty($redisResult['cloud_' . $mac . "_" . $deviceType . "_woman"]))
            {

                $sensorWomanRes = @unserialize($redisResult['cloud_' . $mac . "_" . $deviceType . "_woman"]);
                if (!empty($sensorWomanRes))
                {

                    foreach ($sensorWomanRes as $key => $value)
                    {

                        $woman = @unserialize($value);

                    }
                }

            }

        }

        return [
            'man' => $man,
            'woman' => $woman,
        ];

    }

    /**
     * [getCloudMacData 获取redis数据]
     * @param  [type] $mac [description]
     * @return [type]      [description]
     */
    public function getCloudMacData($mac)
    {
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        return $redis->hgetall('cloud_' . $mac);
    }

    /**
     * [deviceToEasy description]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function deviceToEasy($data)
    {
        foreach ($data as $key => $value) {
            $data[$key] = unserialize($value);
        }
        return $data;
    }

}
